<?php include 'header.php'; ?>
<?php
//이메일 주소 정보를 받아와서 registerForm의 email값에 세팅
require "facebook/facebook.php";
$fb = new Facebook(array(
	"appId"=>"115502678537142",
	"secret"=>"24b002eb0b0b09332bbf635972988504",
        "cookie"=>true
));

$fbUserID = $fb->getUser();
//var_dump($fbUserID);
if($fbUserID) {
$userInfo = $fb->api("/me");
$userEmail = $userInfo["email"];
//echo $userEmail;
}
?>
<script type="text/javascript">
		//<!--
			var latitude;
			var longitude;
			var url = "http://gilstar.com/gilstar/Performance.jsp";
			var req;
			var map;
			var marker;
			
			$(function()
			{
				initTimeSelector();
				initHotspot();
				
			});

			function getMyLocation()
			{
				if(Modernizr.geolocation)	//geolocation support check
				{
					navigator.geolocation.getCurrentPosition(showMap, handleError, {enableHighAccuracy : true, maximumAge : 75000});
				}
				else
				{
					alert("위치정보 서비스가 지원되지 않습니다.");
				}
			}

			function initHotspot() 
			{
				var obj = new Object();
				obj.req = "GET_HOTSPOT_LIST";
				req = obj.req;
				
				getJSON(url, obj);
			}

			function initTimeSelector()
			{
				var d = new Date();
				
				var currHour = d.getHours();
				var currMinute = d.getMinutes();
				//set hour
				for(var i= 0; i <= 23; i++)
				{
					$("#hour").append(new Option(i, i));
				}
				//set minite
				for(var j = 0; j <= 59; j++)
				{
					$("#minute").append(new Option(j, j));
				}

				//$("#hour option")val(currHour).attr("selected", "selected");
			}

			function showMap(position)
			{
				latitude = position.coords.latitude;	//십진법 각도
				longitude = position.coords.longitude;	//십진법 각도.
				
				var currentLocation = new google.maps.LatLng(latitude, longitude);
				
				var myOptions = { zoom: 15, center: currentLocation, mapTypeId: google.maps.MapTypeId.ROADMAP };
				map = new google.maps.Map(document.getElementById("mapView"), myOptions);

				marker = new google.maps.Marker(
					{
							position : currentLocation,
							title : "my location",
							map : map
					});
				
				google.maps.event.addListener(map, 'dragstart', function() {
					removeMarker();
				});

				 google.maps.event.addListener(map, 'dragend', function(){    // 드래그시 이벤트 추가
				        markMapCenter();
				    });
			}

			function removeMarker()
			{
				marker.setMap(null);
			}

			function markMapCenter()
			{
				var pos = map.getCenter();
				latitude = pos.lat();
				longitude = pos.lng();
				var currentLocation = new google.maps.LatLng(latitude, longitude);
				
				marker = new google.maps.Marker(
						{
								position : currentLocation,
								title : "my location",
								map : map
						});
			}
			
			function handleError(err)
			{
				var code = err.code;
				//code의 종류에 1번은 사용자가 위치정보를 공유안함, 2번은 네트워크에 문제 발생, 3번은 시간이 너무 오래 걸림
				//4번은 알 수 없는 오류 발생.
				var message = err.message;		//최종 사용자를 위한 용도가 아님. 
				//alert(err);
				//alert("위치정보 공유가 거부되었습니다.");
				
				var latLng = ($("#concertLocation option").val()).split(",");
				
				var position = new Object();
				position.coords = new Object();
				position.coords.latitude = latLng[0];
				position.coords.longitude = latLng[1];
				showMap(position); 
			}

			function getAddress()
			{
				var o = new Object();
				o.req = "GET_ADDRESS";
				o.latitude = latitude;
				o.longitude = longitude;
				req = o.req;
				
				getJSON(url, o);
			}
				
		
			function registPerformance()
			{
				
				var so = $("form[name=registerForm]").serializeArray();
				var o = {};
				var time = "";
				$.each(so, function()
					{
						var key = this.name;
						var value;
						
						if(this.value != null)
						{
							value = this.value;
						}
						else
						{
							value = "";
						}
						if(key == "title" || key == "artist" || key == "content" || key == "address")
						{
							value = encodeURL(value);
						}
						else if(key == "date")
						{
							var d = new Date();
							if(value == "today")
							{
								value = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate(); 
							}
							else
							{
								value = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + (d.getDate() + 1);
							}
						}
						else if(key == "hour")
						{
							time += value + ":";
						}
						else if(key == "minute")
						{
							time += value;
							o["time"] = time;
						}
						else if(key == "latitude")
						{
							value = latitude;
						}
						else if(key == "longitude")
						{
							value = longitude;
						}
						else if(key == "req")
						{
							req = value;
						}
						else if(key == "sns_url")
						{
							value = $("#signupSNS").val() + value;
						}
						o[key] = value;
					});

				
				getJSON(url, o);
			}

			function getJSON(url, json)
			{
				var requestStr = JSON.stringify(json, replacer);
				$.ajax(
					{
						url: url,
						data: requestStr,
						type: "POST",
						success: function(data)
						{
							var resultObject = jQuery.parseJSON(data);
							jsonResponseHandler(resultObject);
						}
					});
			}
			
			function jsonResponseHandler(result)
			{
				if(result.ResultCode == -1)			//처리 도중 실패.
				{
					alert("error : " + result.ResultMessage);
				}
				else if(result.ResultCode == 0)	//성공적으로 처리 완료.
				{
					if(req == "REGISTER_PERFORMANCE")
					{
						var performance_seq = result.ResultMethod[0].performance_seq;
						
						$("[name=performance_seq]").val(performance_seq); 
						
						if($("[name=file]").val() != "")
						{
							document.fileUploadForm.submit();
						}
						else
						{
							location.href="http://gilstar.com/main/view.php?performance_seq=" + performance_seq;
						}
					}
					else if(req == "GET_ADDRESS")
					{
						//alert(JSON.stringify(result, replacer));
						//alert(result.ResultMethod);
						$("[name=address]").val(result.ResultMethod);
						registPerformance();
					}
					else if(req == "GET_HOTSPOT_LIST")
					{
						for(var nIndex = 0; nIndex < result.ResultMethod.length; nIndex++) 
						{
							spot = result.ResultMethod[nIndex];	//access by array index.
							var options = new Option(spot.name, (spot.latitude + ',' + spot.longitude));
							$("#concertLocation").append(options);
						}
						getMyLocation();
					}
					
				}
			}

			function replacer(key, value) 
			{
			    if (typeof value === 'number' && !isFinite(value)) 
			    {
			        return String(value);
			    }
			    return value;
			}

			function encodeURL(str)
			{
			    var s0, i, s, u;
			    s0 = "";                // encoded str
			    for (i = 0; i < str.length; i++)
			    {
			        s = str.charAt(i);
			        u = str.charCodeAt(i);          // get unicode of the char
			        if (s == " ")
			        {
			        	s0 += "20";	// SP should be converted to "+"
			        }
			        else 
			        {
		                if ((u >= 0x0) && (u <= 0x7f))    // single byte format
		                {
		                    s = "0"+u.toString(16);
		                    s0 += s.substr(s.length-2);
		                }
		                else if (u > 0x1fffff)	// quaternary byte format (extended)
		                {    
		                    s0 += (oxf0 + ((u & 0x1c0000) >> 18)).toString(16);
		                    s0 += (0x80 + ((u & 0x3f000) >> 12)).toString(16);
		                    s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
		                    s0 += (0x80 + (u & 0x3f)).toString(16);
		                }
		                else if (u > 0x7ff)	// triple byte format
		                {        
		                    s0 += (0xe0 + ((u & 0xf000) >> 12)).toString(16);
		                    s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
		                    s0 += (0x80 + (u & 0x3f)).toString(16);
		                }
		                else 			// double byte format
		                {                      
		                    s0 += (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
		                    s0 += (0x80 + (u & 0x3f)).toString(16);
		                }
			        }
			    }

			    return s0;
			}


			function handleSns(item)
			{
				if(item.value == "")
				{
					$("#sns_url").val("http://");
				}
				else
				{
					$("#sns_url").val("");
				}
			}

			function handleChangeLocation(item)
			{
				var location = item.value;
				var latLng = location.split(",");

				var position = new Object();
				position.coords = new Object();
				position.coords.latitude = latLng[0];
				position.coords.longitude = latLng[1];
				showMap(position); 
			}
		//-->
		</script>
<!-- 공연 등록 -->
<section id="signup"> 
	<h1 class="hidden">공연 등록</h1> 
	<form action="#" name="registerForm"> 
		<input type="hidden" name="req" value="REGISTER_PERFORMANCE">
			<?php 
			if (empty($userEmail) == true)
			{
				echo "<input type=\"hidden\" name=\"email\">";
			}
			else
			{
				echo "<input type=\"hidden\" name=\"email\" value=\"" . $userEmail . "\">";
			}
			?>
			
		<input type="hidden" name="latitude">
		<input type="hidden" name="longitude">
		<input type="hidden" name="address">
		<fieldset class="writeRequired"> 
			<legend class="hidden">필수 입력</legend> 
			<ul class="writeUl"> 
			<li class="writeLi"> 
				<label class="writeCell" for="signupTitle">제목</label> 
				<span class="writeCell"> 
					<span class="writeView"><input type="text" class="writeInput" id="signupTitle" name="title" required></span> 
				</span> 
			</li> 
			<li class="writeLi"> 
				<label class="writeCell" for="signupArtist">아티스트명</label> 
				<span class="writeCell"> 
					<span class="writeView"><input type="text" class="writeInput" id="signupArtist" name="artist" required></span> 
				</span> 
			</li> 
			<li class="writeLi"> 
				<label class="writeCell" for="playType">공연 종류</label> 
				<span class="writeCell"> 
					<select id="playType" class="select" name="category">
						<option value="music" selected>음악 공연</option>
	    				<option value="performance">행위 공연</option>
	    				<option value="exhibition">전시 공연</option>
	    				<option value="others">기타 공연</option>
					</select>
				</span>
			</li> 
			<li class="writeLi"> 
				<span class="writeCell">시작 시간</span> 
				<span class="writeCell"> 
					<label class="writeSpace"><input type="radio" name="date" value="today" checked>오늘</label> 
					<label class="writeSpace"><input type="radio" name="date" value="tomorrow">내일</label> 
					<span class="writeTime">
						<label class="writeSpace">
							<select name="hour" id="hour">
							<option>09</option>
							</select> 시
						</label> 
						<label class="writeSpace">
							<select name="minute" id="minute">
							<option>55</option>
							</select> 분
						</label>
					</span>	
				</span> 
			</li>
			<li>
				<div class="writeLi">
					<label for="concertLocation" class="writeCell">공연 위치</label>
					<span class="writeCell">
						<select id="concertLocation" class="select" onchange="handleChangeLocation(this)">
						<!-- 
						<option value="37.5522,126.923">홍대 프리마켓</option>
						<option value="37.​533​022​,12​7.0​641​16">홍대 걷고싶은 거리</option>
						<option value="37.5553,126.924">대학로 마로니에 공원</option>
						<option value="37.​581​478​,12​7.0​022​17">혜화역 2번 출구</option>
						<option value="36.​430​122​,12​8.0​566​41">홍대</option>
						<option value="37.​551​558​,12​6.9​249​75">홍대 놀이터</option>
						<option value="35.​160​168​,12​9.0​602​96">(부산)쥬디스 태화</option>
						<option value="35.​877​019​,12​8.5​738​13">(대구 동성로)중앙치안센터</option>
						 -->
						</select> 
					</span>
					<span class="writeCell writeCellBlank"></span>
					<span class="writeCell writeCellBtnLocation">
						<button type="button" class="writeBtnLocation" onclick="getMyLocation();">현재 위치</button>
					</span> 
				</div>
				<div class="writeMapArea">
					<div class="writeMap" id="mapView" >
					</div>
				</div> 
				<p class="writeMapNotice">핀이 아닌 지도를 이동해주세요.^^</p>
			</li>
			</ul>
		</fieldset> 
		<fieldset class="writeAdd"> 
			<legend class="hidden">추가 정보</legend> 
			<ul class="writeUl"> 
			<li class="writeLi"> 
				<span class="writeCell"> 
					<label for="signupIntro">소개글</label> 
					<span class="writeView"><textarea cols="50" rows="4" id="signupIntro" placeholder="소개글을 입력하세요. (최대 150자)" class="writeInput writeTextarea" name="content"></textarea></span> 
				</span> 
			</li> 
			<li class="writeLi"> 
				<label class="writeCell" for="signupYoutube">Youtube</label> 
				<span class="writeCell"> 
					<span class="writeView"><input type="url" class="writeInput" value="http://" id="signupYoutube"  name="youtube_link"></span> 
				</span> 
			</li> 
			<li class="writeLi"> 
				<label class="writeCell" for="signupSNS">SNS URL</label> 
				<span class="writeCell writeCellSNS"> 
					<select id="signupSNS" class="select" onchange="handleSns(this)">
					<option value="http://www.facebook.com/" selected>페이스북</option>
					<option value="http://tiwitter.com/" >트위터</option>
					<option value="">직적입력</option>
					</select>
				</span> 
				<span class="writeCell writeCellBlank"></span>
				<span class="writeCell"> 
					<span class="writeView"><input type="url" class="writeInput" placeholder="해당 주소" id="sns_url" name="sns_url"></span> 
				</span> 
			</li> 
			</ul> 
		</fieldset> 
	</form> 
	<div class="writeFile"> 
		<form action="http://gilstar.com:8080/gilstar/FileUpload.jsp" method="post" enctype="multipart/form-data" name="fileUploadForm">
		<input type="hidden" name="performance_seq" id="performance_seq">
		<input type="file" title="이미지 첨부하기" class="writeFileInput" name="file">
		</form>
		<?php if($uacssValue=='safari') echo '<p class="writeFileNotice">아이폰 Safari에서는 첨부파일을 지원하지 않습니다.</p>'; ?>
	</div> 
	<div class="action">
		<p class="actionNotice">로그인하지 않은 상태에서 등록하시면 삭제가 불가능합니다.</p> 
		<div class="btnSubmitWrap"><button type="button" class="btnSubmit" onclick="getAddress();">등록하기</button></div>
	</div>
</section> 
<!-- //공연 등록 --> 

<?php include 'footer.php'; ?>